package com.xbongbong.parent.parse.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EsAliasEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.UserHelper;
import com.xbongbong.paas.model.ContractEditFileModel;
import com.xbongbong.paas.model.ContractTemplateBaseModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.dto.AnalysisDataDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.parent.abstracts.AbstractFormDataAnalysisDataHelp;
import com.xbongbong.parent.abstracts.AbstractSpecialDataAnalysisHelp;
import com.xbongbong.parent.help.AnalysisTemplateFieldHelp;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.customer.pojo.CustomerMainContactPojo;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.dto.FormConfigGetDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.label.pojo.LabelForDetailUpadatePojo;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.onlineEditor.TemplateFieldValuePojo;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractEditFileEntity;
import com.xbongbong.saas.domain.entity.ContractTemplateBaseEntity;
import com.xbongbong.saas.enums.BusinessFieldEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticEnum;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.VisibleRangeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.*;
import com.xbongbong.saas.enums.dictionary.IsRedEnum;
import com.xbongbong.saas.help.DistributorListHelp;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.impl.PublicGroupSeniorModelImpl;
import com.xbongbong.saas.service.toolbox.help.AnalysisSaasDataListHelp;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.saas.util.UserFieldUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 获取数据列表时解析数据
 * @author: wufeng
 * @date: 2018/12/5 9:44
 * @desrcption: 解析数据
 */
@Component
public class FormDataListAnalysisDataHelp extends AbstractFormDataAnalysisDataHelp {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataListAnalysisDataHelp.class);

    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private FormDataLinkDataListServiceImpl formDataLinkDataListService;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private FormDataFastUpdateAnalysisDataHelp formDataFastUpdateAnalysisDataHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private AnalysisSaasDataListHelp analysisSaasDataListHelp;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private DistributorListHelp distributorListHelp;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    @Lazy
    private Map<String, AbstractSpecialDataAnalysisHelp> webDataAnalysisHandleMap;
    @Resource
    private PublicGroupSeniorModelImpl publicGroupSeniorModel;
    @Resource
    private AnalysisTemplateFieldHelp analysisTemplateFieldHelp;

    /**
     * 解析数据
     * @param formDataListVO
     * @throws XbbException
     */
    public void analysisDataList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {

        try {
            List<PaasFormDataEntityExt> formDataEsList = formDataListVO.getPaasFormDataESList();
            List<FieldAttrEntity> explainList = formDataListVO.getHeadList();

            List<Long> dataIdList = new ArrayList<>();
            Set<String> userIdList = UserFieldUtil.getUserIdList(formDataEsList, explainList, dataIdList);

            Integer businessType4Distributor = XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(), formDataListDTO.getDistributorMark());
            formDataListDTO.setBusinessType(businessType4Distributor);
            String corpid = formDataListDTO.getCorpid();

            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> paasCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Integer businessType = formDataListDTO.getBusinessType();
            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            //待出库特殊处理
            if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())){
                    businessType = XbbRefTypeEnum.CONTRACT.getCode();
                }
            }
            if (UserTeamEnum.hasTeam(businessType)){
                Boolean isPublic = (Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(),subBusinessType));
                businessUserTeamHelp.getUserIdMapSetShow(userIdList,dataIdList,corpid,businessType,isPublic,mainUserMap,coUserMap, DelEnum.NORMAL.getDel());
            } else {
                paasCoUserMap = businessUserTeamHelp.coUserMapShow(userIdList,dataIdList, formDataListDTO.getCorpid());
            }

            List<UserEntity> userEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, Object> param = BeanUtil.convertBean2Map(formDataListDTO, true);
            param.remove("del");
//            param.put("del",0);
            param.put("userIdIn",userIdList);
            param.put(ParameterConstant.COLUMNS, "user_id, name");
            param.put(ParameterConstant.LEAVE_MARKS,BasicConstant.ONE);
            List<UserEntity> userList = userModel.findEntitys(param);
            userEntityList.addAll(userList);

            if(userEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
            }
            Map<String, UserEntity> userMap = new HashMap<>(userEntityList.size());
            userEntityList.forEach((item)->{
                userMap.put(item.getUserId(), item);
            });

            Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            boolean departmentMapIsEmpty = hasDepartment(explainList);
            if(departmentMapIsEmpty){
                param.clear();
                param = BeanUtil.convertBean2Map(formDataListDTO, true);
                param.remove("del");
                param.put(ParameterConstant.COLUMNS, "id, name");
                List<DepartmentEntity> departmentList = departmentModel.findEntitys(param);
                if (departmentList == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DEPT_NOT_EXIST);
                }
                departmentList.forEach((departmentItem) -> {
                    departmentMap.put(departmentItem.getId().toString(), departmentItem);
                });
            }
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(formDataListVO.getHeadList().size());
            for (FieldAttrEntity item : formDataListVO.getHeadList()) {
                explainMap.put(item.getAttr(), item);
            }
            //将采购合同中应收、未收与采购金额可见权限一致
            if (Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode()) && Objects.equals(subBusinessType,XbbRefTypeEnum.PURCHASE.getCode()) && explainMap.containsKey(PurchaseEnum.TOTAL_MONEY.getAttr())){
                VisibleRulePoJo visibleRulePoJo = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisibleScopeRule();
                Integer visibleScopeEnable = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisibleScopeEnable();
                Integer visible = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisible();
                if(Objects.equals(visibleScopeEnable,BasicConstant.ONE)){
                    //处理实付金额
                    FieldAttrEntity fieldAttrEntity = explainMap.get(PurchaseEnum.FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.FINISH_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理未付金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.UN_FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.UN_FINISH_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理坏账金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.BAD_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.BAD_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理收款比例
                    fieldAttrEntity = explainMap.get(PurchaseEnum.RECEINE_PERCENT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.RECEINE_PERCENT.getAttr(),fieldAttrEntity);
                    }
                    //处理开票金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.INVOICE_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.INVOICE_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理未开票金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                }
            }
            //将合同订单中应收、未收与合同金额可见权限一致
            if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) && Objects.equals(subBusinessType,XbbRefTypeEnum.CONTRACT.getCode()) && explainMap.containsKey(ContractEnum.AMOUNT.getAttr())){
                VisibleRulePoJo visibleRulePoJo = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisibleScopeRule();
                Integer visibleScopeEnable = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisibleScopeEnable();
                Integer visible = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisible();
                if (Objects.equals(visibleScopeEnable,BasicConstant.ONE)){
                    //处理实付金额
                    FieldAttrEntity fieldAttrEntity = explainMap.get(ContractEnum.FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.FINISH_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理未付金额
                    fieldAttrEntity = explainMap.get(ContractEnum.UN_FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.UN_FINISH_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理坏账金额
                    fieldAttrEntity = explainMap.get(ContractEnum.BAD_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.BAD_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理收款比例
                    fieldAttrEntity = explainMap.get(ContractEnum.PAY_PERCENT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.PAY_PERCENT.getAttr(), fieldAttrEntity);
                    }
                    //处理开票金额
                    fieldAttrEntity = explainMap.get(ContractEnum.INVOICE_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.INVOICE_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理未开票金额
                    fieldAttrEntity = explainMap.get(ContractEnum.UN_INVOICE_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.UN_INVOICE_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                }
            }
            LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
            Set<Object> linkDataSet = new HashSet<>();
            List<PaasFormDataEntityExt> linkDataList = new ArrayList<>();


            Map<Long, Boolean> contactPhoneMap = null;
            // 客户主联系人处理
            if(Objects.equals(SaasMarkEnum.SAAS.getCode(), formDataListDTO.getSaasMark()) &&
                    Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getBusinessType())) {
                contactPhoneMap = analysisContactForCustomer(corpid, formDataListDTO, dataIdList);
            }

            FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
            formConfigGetDTO.setCorpid(corpid);
            formConfigGetDTO.setBusinessType(businessType);
            formConfigGetDTO.setFormId(formDataListDTO.getFormId());
            Map<String, String> lastConnectTimeMap = lastConnectTime(formConfigGetDTO);
            // 标签处理
            List<FieldAttrEntity> headList = formDataListVO.getHeadList();
            String labelAttr =null;
            for (FieldAttrEntity fieldAttrEntity : headList) {
                if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    labelAttr = fieldAttrEntity.getAttr();
                    break;
                }
            }
            List<Long> labelIds = new ArrayList<>();
            if (StringUtil.isNotEmpty(labelAttr)){
                for (PaasFormDataEntityExt paasFormDataEntityExt : formDataEsList) {
                    Object o = null;
                    if(Objects.nonNull(paasFormDataEntityExt.getData().get(labelAttr))) {
                        o = paasFormDataEntityExt.getData().get(labelAttr);
                        List<Object> labelList = JSONArray.parseArray(o.toString(), Object.class);
                        if (CollectionsUtil.isNotEmpty(labelList)) {
                            for (Object labelId : labelList) {
                                //兼容存在脏数据UUID
                                if (Objects.nonNull(labelId) && !ItemUtil.isUUID(labelId.toString())) {
                                    labelIds.add(Long.valueOf(labelId.toString()));
                                }
                            }
                        }
                    }
                }
            }
            List<LabelEntity> byLabelIds = null;
            Map<Long, LabelEntity> labelMap= new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(labelIds)) {
                byLabelIds = labelModel.getByLabelIds(labelIds, corpid);
                byLabelIds.forEach(item->{
                    labelMap.put(item.getId(), item);
                });
            }
            // 订货单处理
            boolean isOrder = Objects.equals(XbbRefTypeEnum.ORDER.getCode(),businessType);
            Map<String,Map<Long, List<JSONObject>>> productAttr2Map = new HashMap<>();
            if (Objects.equals(XbbRefTypeEnum.ORDER.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.RETURN.getCode(), businessType)) {
                CustomerMainContactPojo customerMainContactPojo = new CustomerMainContactPojo();
                AbstractSpecialDataAnalysisHelp abstractSpecialDataAnalysisHelp = webDataAnalysisHandleMap.get(businessType);
                if (Objects.nonNull(abstractSpecialDataAnalysisHelp)) {
                    customerMainContactPojo = abstractSpecialDataAnalysisHelp.getSpecialData(formDataListDTO, formDataListVO);
                }
                if (Objects.nonNull(customerMainContactPojo.getCustomerFieldList())) {
                    formDataListVO.setHeadList(customerMainContactPojo.getCustomerFieldList());
                }
                productAttr2Map = customerMainContactPojo.getProductAttr2Map();
            }
            // 库存查询多单位
            boolean isStockSearch = Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && StockConstant.STOCK_SEARCH_TYPE_LIST.contains(formDataListDTO.getSubBusinessType());
            Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
            Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
            // 经销商账号管理处理
            boolean isDistributorAccount = Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode());
            if (isDistributorAccount) {
                distributorAccountModel.setDistributorName(formDataEsList, corpid);
            }
            // 经销商档案处理
            Map<Long, String> areaMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, Object> purchaseableGoodsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            boolean isDistributor = Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode());
            if (isDistributor) {
                areaMap = distributorListHelp.areaList(formDataListDTO.getCorpid());
                purchaseableGoodsMap = distributorListHelp.purchaseableGoodsList(formDataListDTO.getCorpid());
            }
            Map<Long, LabelPojo> labelPojoMap = labelHelp.getLabelMap(formDataListDTO.getFormId(), formDataListDTO.getCorpid(), formDataListDTO.getAppId());

            Map<Object, TemplateFieldValuePojo> templateFieldMap = analysisTemplateFieldHelp.getTemplateFieldMap(corpid, headList, formDataEsList);
            for (PaasFormDataEntityExt paasFormDataEsEntity : formDataEsList) {
                JSONObject dataJsonObject = paasFormDataEsEntity.getData();
                if (Objects.nonNull(paasFormDataEsEntity.getOriginData())) {
                    dataJsonObject = paasFormDataEsEntity.getOriginData();
                    paasFormDataEsEntity.setOriginData(null);
                }
                dataJsonObject.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEsEntity.getAddTime());
                dataJsonObject.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEsEntity.getUpdateTime());
                //待入库待出库特殊处理
                if ((Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())||
                        Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) && Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                }else {
                    dataJsonObject.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                }
                // 客户最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) ){
                    dataJsonObject.put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig()));

                }
                // 销售机会最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
                    dataJsonObject.put(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig()));
                }
                // 线索最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                    dataJsonObject.put(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig()));
                }
                // 订货单
                if (isOrder && productAttr2Map.containsKey(OrderEnum.PRODUCT.getAttr()) && CollectionsUtil.isNotEmpty(productAttr2Map.get(OrderEnum.PRODUCT.getAttr()).get(paasFormDataEsEntity.getDataId()))) {
                    dataJsonObject.put(ContractEnum.PRODUCT.getAttr(), productAttr2Map.get(ContractEnum.PRODUCT.getAttr()).get(paasFormDataEsEntity.getDataId()));
                }

                dataJsonObject.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEsEntity.getDepartmentId());
                dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), paasFormDataEsEntity.getOwnerId());

                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataListDTO, parseSingleRowDataDTO);
                dataJsonObject.put(FieldTypeEnum.CREATORID.getAlias(), paasFormDataEsEntity.getCreatorId());
                // 设置创建人
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                    parseSingleRowDataDTO.setCreatorId(dataJsonObject.getString(CustomerManagementEnum.CREATOR.getAttr()));
                } else {
                    parseSingleRowDataDTO.setCreatorId(paasFormDataEsEntity.getCreatorId());
                }
                setOwnerIdAndCoUserId(businessType, dataJsonObject, parseSingleRowDataDTO, paasFormDataEsEntity, mainUserMap, coUserMap, paasCoUserMap);
                JSONObject cloneData = (JSONObject)dataJsonObject.clone();
                Long dataId = paasFormDataEsEntity.getId();
                paasFormDataEsEntity.setDataId(dataId);

                parseSingleRowDataDTO.setDataJsonObject(dataJsonObject);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setListFlag(1);
                parseSingleRowDataDTO.setDataId(dataId);
                parseSingleRowDataDTO.setFormId(paasFormDataEsEntity.getFormId());
                parseSingleRowDataDTO.setTemplateFieldMap(templateFieldMap);
                // 解析单行数据
                ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(parseSingleRowDataVO)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                JSONObject resultObject = parseSingleRowDataVO.getResult();
                if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
                    if (Objects.isNull(resultObject.get(ProductEnum.UNIT.getAttr()))) {
                        if (Objects.nonNull(resultObject.get("transformUnitRate"))) {
                            resultObject.put("transformUnitRate", null);
                        }
                    }
                }
                if (!linkResultDataVO.getLinkDataSet().isEmpty()) {
                    linkResultDataVO.getLinkDataSet().forEach((item -> {
                        linkDataSet.add(item);
                    }));
                }
                // 库存查询多单位
                if (isStockSearch) {
                    if (BasicConstant.ONE.equals(cloneData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        String unitStr = "";
                        if (PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform())) {
                            unitStr = cloneData.getString(ProductEnum.UNIT.getAttr());
                        } else if (PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())){
                            unitStr = cloneData.getString(ProductEnum.UNIT.getSaasAttr());
                        }
                        if (StringUtil.isNotEmpty(unitStr)) {
                            MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.getOrDefault(Long.parseLong(unitStr), new MultiUnitItemPoJo());
                            resultObject.put(ProductEnum.UNIT.getAttr(), multiUnitItemPoJo.getBaseName());
                            List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(Long.parseLong(unitStr));
                            resultObject.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                        }
                    }
                }
                parseSingleRowDataDTO.setDataJsonObject(cloneData);
                // 为了在列表上面可以更新数据，加下这个
                ParseSingleRowDataVO updateDataVo = formDataFastUpdateAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(updateDataVo)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                JSONObject sourceData = updateDataVo.getResult();
                sourceData.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                if (!sourceData.containsKey(FieldTypeEnum.DEPARTMENTID.getAlias())) {
                    sourceData.put(FieldTypeEnum.DEPARTMENTID.getAlias(), -1);
                }
                paasFormDataEsEntity.setSourceData(sourceData);
                formDataListVO.getHeadList().forEach((item) -> {
                    if (!resultObject.containsKey(item.getAttr())) {
                        if (FieldTypeEnum.SUB_FORM.getType().equals(item.getFieldType())
                                || FieldTypeEnum.UPLOAD.getType().equals(item.getFieldType())
                                || FieldTypeEnum.IMAGE.getType().equals(item.getFieldType())
                                || FieldTypeEnum.CONTACT_NUMBER.getType().equals(item.getFieldType())) {
                            resultObject.put(item.getAttr(), new ArrayList<>());
                        } else {
                            resultObject.put(item.getAttr(), "");
                        }
                    }
                });
                // 经销商
                if (isDistributor) {
                    // 所在地区
                    String areaAttr = DistributorEnum.AREA.getAttr();
                    Long areaId = resultObject.getLong(areaAttr);
                    if (Objects.nonNull(areaId)) {
                        resultObject.put(areaAttr, areaMap.getOrDefault(areaId, ""));
                    }
                    // 可采购商品
                    StringBuilder purchaseableGoodsAll = new StringBuilder();
                    String purchaseableGoodsAttr = DistributorEnum.PURCHASEABLE_GOODS.getAttr();
                    JSONArray purchaseableGoodsArr = resultObject.getJSONArray(purchaseableGoodsAttr);
                    if (CollectionsUtil.isNotEmpty(purchaseableGoodsArr)) {
                        for (Object purchaseableGoodsId : purchaseableGoodsArr) {
                            Object goodsNameObj = purchaseableGoodsMap.get(purchaseableGoodsId.toString());
                            String purchaseableGoodsName = goodsNameObj instanceof String ? (String) goodsNameObj : "";
                            purchaseableGoodsAll.append(purchaseableGoodsName).append(",");
                        }
                        // 移除最后一个逗号
                        purchaseableGoodsAll.deleteCharAt(purchaseableGoodsAll.length() - 1);
                        resultObject.put(purchaseableGoodsAttr, purchaseableGoodsAll);
                    } else {
                        resultObject.put(purchaseableGoodsAttr, "");
                    }
                }
                // 主联系人电话不可见时，设置为*****
                if(contactPhoneMap != null && contactPhoneMap.containsKey(dataId) && resultObject.containsKey(CustomerManagementEnum.CONTACT_PHONE.getAttr())) {
                    boolean seePhone = contactPhoneMap.get(dataId);
                    if(!seePhone) {
                        JSONArray contactArray = resultObject.getJSONArray(CustomerManagementEnum.CONTACT_PHONE.getAttr());
                        if(Objects.nonNull(contactArray) && !contactArray.isEmpty()) {
                            for(int i = 0; i < contactArray.size(); i++) {
                                JSONObject phoneObj = contactArray.getJSONObject(i);
                                if(phoneObj.containsKey("text_2")) {
                                    phoneObj.put("text_2", "*****");
                                }
                            }
                        }
                        resultObject.put(CustomerManagementEnum.CONTACT_PHONE.getAttr(), contactArray);
                    }
                }
                labelHelp.dealId2Pojo4One(labelAttr,resultObject, labelPojoMap);
                // 线索最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                    dataJsonObject.put(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig()));
                }
                paasFormDataEsEntity.setData(resultObject);
                // 移动端，客户、机会、合同、报价单 加上 ‘归’ 字标签 (注：web端tagData已经赋过值，不做处理)
                setAchived(formDataListDTO, resultObject, paasFormDataEsEntity);
                //评分列表页展示
                handleWebListScoreShowValue(businessType,paasFormDataEsEntity);
                // 系统字段经历过一次权限的判断，所以这里加下重新赋值
                paasFormDataEsEntity.setSerialNo(resultObject.getString(FieldTypeEnum.SERIALNO.getAlias()));
                paasFormDataEsEntity.setCreatorId(resultObject.getString(FieldTypeEnum.CREATORID.getAlias()));
                paasFormDataEsEntity.setAddTime(resultObject.getLong(FieldTypeEnum.ADDTIME.getAlias()));
                paasFormDataEsEntity.setUpdateTime(resultObject.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
                paasFormDataEsEntity.setOwnerId(resultObject.getString(FieldTypeEnum.OWNERID.getAlias()));
                paasFormDataEsEntity.setAdvancePaymentBalance(paasFormDataEsEntity.getAdvancePaymentBalance());
                if (Objects.isNull(resultObject.get(FieldTypeEnum.DEPARTMENTID.getAlias()))) {
                    paasFormDataEsEntity.setDepartmentId(null);
                }

                linkDataList.add(paasFormDataEsEntity);
            }
            // 获取关联数据
            linkResultDataVO.setExplainMap(explainMap);
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            linkResultDataVO.setLinkDataSet(linkDataSet);
            linkResultDataVO.setFormDataList(linkDataList);
            linkResultDataVO.setExplainList(formDataListVO.getHeadList());
            if(!linkDataSet.isEmpty()){
                LinkResultDataDTO linkResultDataDTO = new LinkResultDataDTO();
                BeanUtil.copyProperties(formDataListDTO, linkResultDataDTO);
                formDataLinkDataListService.formDataLinkDataGet(linkResultDataDTO, linkResultDataVO);
            }
            formDataListVO.setPaasFormDataESList(linkResultDataVO.getFormDataList());
        } catch (XbbException e) {
            LOG.error("formDataListAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("formDataListAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    /**
     * web列表评分showValue处理
     * @param businessType
     */
    public void handleWebListScoreShowValue(Integer businessType , PaasFormDataEntityExt paasFormDataEsEntity) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        //处理评分(按照评分规则的展示区间来)
        if(XbbRefTypeEnum.checkScoreBusinessType(businessType)){
            String scoreShowValue = scoreRangeModel.getScoreShowValue(businessType, paasFormDataEsEntity);
            switch (xbbRefTypeEnum){
                case CUSTOMER_MANAGEMENT:
                    paasFormDataEsEntity.getData().put(CustomerManagementEnum.SCORE.getAttr(), scoreShowValue);
                    break;
                case CLUE:
                    Object o = paasFormDataEsEntity.getData().get(ClueEnum.SCORE.getAttr());
                    if(o==null){
                        paasFormDataEsEntity.getData().put(ClueEnum.SCORE.getAttr(), scoreShowValue);
                    }
                    break;
            }
        }
    }

    /**
     * 判断含有部门字段
     * @param explainList
     * @return true: 有部门字段 false：无部门字段
     */
    public Boolean hasDepartment(List<? extends FieldAttrEntity> explainList) {
        Boolean hasDepartment;
        for (FieldAttrEntity item : explainList) {
            hasDepartment = FieldTypeEnum.DEPT.getType().equals(item.getFieldType())
                    || FieldTypeEnum.DEPT_GROUP.getType().equals(item.getFieldType())
            || FieldTypeEnum.DEPARTMENTID.getType().equals(item.getFieldType());
            if (hasDepartment) {
                return true;
            } else if (ExplainUtil.isSubForm(item.getFieldType())) {
                SubFormPoJo subForm = item.getSubForm();
                if (subForm != null && subForm.getItems() != null) {
                    List<? extends FieldAttrEntity> subExplainList = subForm.getItems();
                    hasDepartment = hasDepartment(subExplainList);
                }
                if (hasDepartment) {
                    return true;
                }
            }
        }
        return false;
    }

    public void setOwnerIdAndCoUserId(Integer businessType, JSONObject dataJsonObject, ParseSingleRowDataDTO parseSingleRowDataDTO,
                                      PaasFormDataEntityExt paasFormDataEsEntity, Map<Long, List<String>> mainUserMap, Map<Long, List<String>> coUserMap, Map<Long, List<String>> paasCoUserMap) {
        if (UserTeamEnum.hasTeam(businessType)) {
            if (XbbRefTypeEnum.hasVisibleRangeBusiness().contains(businessType)) {
                dataJsonObject.put(VisibleRangeEnum.VISIBLE_USER.getAttr(), mainUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>()));
                dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), Collections.singletonList(paasFormDataEsEntity.getOwnerId()));
                dataJsonObject.put(VisibleRangeEnum.VISIBLE_DEPT.getAttr(), coUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>()));
            } else if (Objects.equals(XbbRefTypeEnum.COMPETITOR.getCode(),businessType)){
                dataJsonObject.put(CompetitorEnum.VISBLE_USER.getAttr(),mainUserMap.getOrDefault(paasFormDataEsEntity.getDataId(),new ArrayList<>()));
                dataJsonObject.put(CompetitorEnum.VISBLE_DEPT.getAttr(), coUserMap.getOrDefault(paasFormDataEsEntity.getDataId(),new ArrayList<>()));
            }
            else {
                List<String> ownerId =  mainUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>());
                if (CollectionUtils.isNotEmpty(ownerId)) {
                    List<String> disOwnerId =  ownerId.stream().distinct().collect(Collectors.toList());
                    dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), disOwnerId);
                } else {
                    dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), new ArrayList());
                }
            }
            // 设置创建人
            List<String> ownerId = mainUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>());
            parseSingleRowDataDTO.setOwnerId(ownerId);
            List<String> coUserId = coUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>());
            if (CollectionUtils.isNotEmpty(coUserId)) {
                List<String> disCoUserId = coUserId.stream().distinct().collect(Collectors.toList());
                dataJsonObject.put(FieldTypeEnum.COUSERID.getAlias(), disCoUserId);
            }
            parseSingleRowDataDTO.setCoUserId(coUserId);
        } else {
            List<String> ownerId = Collections.singletonList(paasFormDataEsEntity.getOwnerId());
            dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), ownerId);
            parseSingleRowDataDTO.setOwnerId(ownerId);
            List<String> coUserId = paasCoUserMap.get(paasFormDataEsEntity.getDataId());
            dataJsonObject.put(FieldTypeEnum.COUSERID.getAlias(), coUserId);
            parseSingleRowDataDTO.setCoUserId(coUserId);
        }
    }

    /**
     * 解析特殊数据，地址，附件，定位，多选转成逗号隔开的字符串
     * @param resultJsonObject
     */
    @Override
    public void analysisData(AnalysisDataDTO analysisDataDTO, JSONObject resultJsonObject,
                             Map<String, Object> linkData, Set<Object> linkDataSet) throws XbbException{

        boolean salesOpportunityLastConnectTime = true;
        // 销售机会最后跟进时间格式标识
        if(Objects.nonNull(resultJsonObject.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getDbAlias()))){
            String lastConnectTime = resultJsonObject.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getDbAlias()).toString();
            salesOpportunityLastConnectTime = Objects.equals(lastConnectTime, "1") ? true : false;
        }

        boolean clueLastConnectTime = true;
        // 线索最后跟进时间格式标识
        if(Objects.nonNull(resultJsonObject.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getDbAlias()))){
            String lastConnectTime = resultJsonObject.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getDbAlias()).toString();
            clueLastConnectTime = Objects.equals(lastConnectTime, "1") ? true : false;
        }

        FieldAttrEntity fieldAttrEntity = analysisDataDTO.getFieldAttrEntity();
        String key = analysisDataDTO.getAttr();
        JSONObject objectJsonObject = analysisDataDTO.getDataJsonObject();
        Map<String, UserEntity> userMap =analysisDataDTO.getUserMap();
        Map<String, DepartmentEntity> departmentMap= analysisDataDTO.getDepartmentMap();
        Integer fieldType = fieldAttrEntity.getFieldType();
        Integer businessType = analysisDataDTO.getBusinessType();
        // 百分比数字字段处理
        String saasAttr = fieldAttrEntity.getSaasAttr();
        String numberType = fieldAttrEntity.getNumberType();
        boolean rateNumFlag = FieldAttrEntity.isRate(saasAttr, numberType);
        // 判断高级规则
        boolean invisibleOfScope = false;
        // 审批摘要不判断高级权限
        if (Objects.isNull(analysisDataDTO.getIsProcess()) || !analysisDataDTO.getIsProcess()) {
            invisibleOfScope = FormDataAnalysisHelp.invisibleSetNull(fieldAttrEntity, analysisDataDTO, objectJsonObject);
        }
        // TODO 关于成员和部门回显需要去掉离职人员，现在直接不限，具体如何显示，未解决
        if(fieldAttrEntity.getFieldType().equals(FieldTypeEnum.HREF.getType())) {
            try {
                resultJsonObject.put(key, JSONObject.parse(objectJsonObject.get(key).toString()));
            }catch (Exception e){

            }
        }else if(fieldAttrEntity.getFieldType().equals(FieldTypeEnum.DATETIME.getType())
                || Objects.equals(fieldType, FieldTypeEnum.ADDTIME.getType())
                || Objects.equals(fieldType, FieldTypeEnum.UPDATETIME.getType())){
            boolean isTrue = (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())
                    && Objects.equals(fieldAttrEntity.getSaasAttr(), SalesOpportunityEnum.LAST_CONNECT_TIME.getSaasAttr()) && salesOpportunityLastConnectTime)
                    || (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())
                    && Objects.equals(fieldAttrEntity.getSaasAttr(), ClueEnum.LAST_CONNECT_TIME.getSaasAttr()) && clueLastConnectTime);
            if (isTrue) {
                resultJsonObject.put(key, DateTimeUtil.getLastConnectTimeStr(objectJsonObject.getLong(key)));
            } else {
                resultJsonObject.put(key, objectJsonObject.getLong(key));
            }
        }else if(FieldTypeEnum.ADDRESS.getType().equals(fieldAttrEntity.getFieldType())) {
            // 前端列表数据需要将省市区分开，所以在这里处理
            JSONObject addressJsonObject = objectJsonObject.getJSONObject(key);
            // 判断详细地址是否需要显示
            setAddress(addressJsonObject, fieldAttrEntity);
            //工单导出时不需要拼接
            if (!Objects.equals(analysisDataDTO.getFromExport(),1)) {
                mergeFullAddressData(key, addressJsonObject, resultJsonObject);
            }
        }else if(FieldTypeEnum.UPLOAD.getType().equals(fieldAttrEntity.getFieldType())){
            List<PaasAttachmentEntityExt> attachmentStrList = formDataAnalysisHelp.analysisAttachmentList(objectJsonObject.getString(key));
            resultJsonObject.put(key, attachmentStrList);
        }else if(FieldTypeEnum.LOCATION.getType().equals(fieldAttrEntity.getFieldType())){
            JSONObject jsonObject = objectJsonObject.getJSONObject(key);
            // 拼接地址
            mergeFullAddressData(key, jsonObject, resultJsonObject);
        } else if((FieldTypeEnum.RADIO_GROUP.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.COMBO.getType().equals(fieldAttrEntity.getFieldType()))) {
            if (Objects.equals(fieldAttrEntity.getSaasAttr(), SelectProductEnum.UNIT.getSaasAttr())) {
                // 关联产品单位特殊处理下
                if (invisibleOfScope) {
                    resultJsonObject.put(key, StringConstant.INVISIBLE_VALUE);
                } else {
                    formDataAnalysisHelp.analysisCombo(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
                }
            }else if (Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.UNIT.getSaasAttr())) {
                // 产品单位特殊处理下
                formDataAnalysisHelp.analysisCombo(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
            } else {
                //单选、下拉单选返回带颜色的ItemPoJO
                formDataAnalysisHelp.analysisComboWithColor(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
            }
        }else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisListStageJsonObjectWithColor(resultJsonObject, analysisDataDTO);
        }else if (Objects.equals(FieldTypeEnum.FIRST_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisStageStayTime(resultJsonObject, fieldAttrEntity.getAttr());
        }else if (Objects.equals(FieldTypeEnum.NOW_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisStageStayTime(resultJsonObject, fieldAttrEntity.getAttr());
        } else if((FieldTypeEnum.CHECKBOX_GROUP.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.COMBO_CHECK.getType().equals(fieldAttrEntity.getFieldType()))) {
            //复选、下拉复选返回带颜色的List<ItemPoJo>
            formDataAnalysisHelp.analysisComboReturnStrWithColor(objectJsonObject, resultJsonObject,fieldAttrEntity);
        } else if(FieldTypeEnum.USER.getType().equals(fieldAttrEntity.getFieldType())
                || Objects.equals(fieldType, FieldTypeEnum.CREATORID.getType())
        ){
            if(StringUtil.isNotEmpty(objectJsonObject.getString(key))){
                String name = "";
                if(Objects.nonNull(userMap.get(objectJsonObject.getString(key)))){
                    name = userMap.get(objectJsonObject.getString(key)).getName();
                } else if (Objects.equals(objectJsonObject.getString(key), StringConstant.NOT_IN_SYSTEM_ID)) {
                    name = objectJsonObject.getString(fieldAttrEntity.getLinkedText());
                    name = name + "(离职)";
                }
                resultJsonObject.put(key, name);
            }else{
                resultJsonObject.put(key, objectJsonObject.getString(key));
            }
        } else if (FieldTypeEnum.COUSERID.getType().equals(fieldAttrEntity.getFieldType())
                || Objects.equals(fieldType, FieldTypeEnum.OWNERID.getType())) {
            List<UserEntity> userList = UserHelper.getUserByKey(key, objectJsonObject, userMap);
            List<String> nameList = new ArrayList<>();
            userList.forEach(item->{
                nameList.add(item.getName());
            });
            resultJsonObject.put(key, StringUtils.join(nameList, "、"));
        }  else if (FieldTypeEnum.USER_GROUP.getType().equals(fieldAttrEntity.getFieldType())) {
            List<UserEntity> userList = UserHelper.getUserByKey(key, objectJsonObject, userMap);
            List<String> nameList = new ArrayList<>();
            userList.forEach(item->{
                nameList.add(item.getName());
            });
            resultJsonObject.put(key, StringUtils.join(nameList, "、"));
        } else if(FieldTypeEnum.DEPT.getType().equals(fieldAttrEntity.getFieldType() )
                || Objects.equals(fieldType, FieldTypeEnum.DEPARTMENTID.getType())){
            if(StringUtil.isNotEmpty(objectJsonObject.getString(key))){
                String name = "";
                if(Objects.nonNull(departmentMap.get(objectJsonObject.getString(key)))){
                    name = departmentMap.get(objectJsonObject.getString(key)).getName();
                }
                resultJsonObject.put(key, name);
            }else {
                resultJsonObject.put(key, objectJsonObject.getString(key));
            }
        } else if (FieldTypeEnum.DEPT_GROUP.getType().equals(fieldAttrEntity.getFieldType())) {
            List<DepartmentEntity> departmentList = UserHelper.getDepartmentByKey(key, objectJsonObject, departmentMap);
            List<String> nameList = new ArrayList<>();
            departmentList.forEach(item->{
                nameList.add(item.getName());
            });
            resultJsonObject.put(key, StringUtils.join(nameList, "、"));
        } else if (FieldTypeEnum.LINK_DATA.getType().equals(fieldAttrEntity.getFieldType())
                && Objects.nonNull(objectJsonObject.get(key))
                && objectJsonObject.get(key) instanceof Number){
            if (Objects.equals(objectJsonObject.getLong(key), 0L)) {
                resultJsonObject.put(key, null);
                return;
            }
            linkData.put(key, objectJsonObject.get(key));
            linkDataSet.add(objectJsonObject.get(key));
            resultJsonObject.put(key, objectJsonObject.get(key));
        } else if (Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldAttrEntity.getFieldType())
                && Objects.nonNull(objectJsonObject.get(key))
                && (objectJsonObject.get(key) instanceof JSONArray || objectJsonObject.get(key) instanceof ArrayList || objectJsonObject.get(key) instanceof List)) {
            JSONArray linkDataArray = objectJsonObject.getJSONArray(key);
            if (CollectionsUtil.isEmpty(linkDataArray)) {
                resultJsonObject.put(key, null);
                return;
            }
            linkData.put(key, objectJsonObject.get(key));
            linkDataSet.addAll(linkDataArray);
            resultJsonObject.put(key, objectJsonObject.get(key));
        } else if(Objects.equals(fieldType,FieldTypeEnum.NUM.getType()) && Objects.nonNull(objectJsonObject.get(key))){
            if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode()) && (Objects.equals(key,ProductEnum.PRICE.getAttr()) || Objects.equals(key,ProductEnum.COST.getAttr()))){
                // 产品的成本和单价可能会显示一个区间 不再这里进行精度控制
                resultJsonObject.put(key, objectJsonObject.get(key));
                try {
                    JSONObject specObj = resultJsonObject.getJSONObject(ListOptionEnum.MULTI_SPEC.getAttr());
                    if (specObj != null) {
                        JSONArray multiSpecArray = specObj.getJSONArray("value");
                        if (multiSpecArray != null) {
                            for (int i = 0; i < multiSpecArray.size(); i++) {
                                JSONObject multiSpecObj = multiSpecArray.getJSONObject(i);
                                if (Objects.equals(key, ProductEnum.COST.getAttr()) && invisibleOfScope) {
                                    multiSpecObj.put("cost", null);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    LOG.error("产品列表页解析数据设置子产品成本字段不可见出错", e);
                }
            } else if(Objects.equals(fieldType,FieldTypeEnum.LABEL.getType()) && Objects.nonNull(objectJsonObject.get(key))){
                analasisLabel(analysisDataDTO, key, objectJsonObject, resultJsonObject );
            } else {
                // 小数精度
                boolean visible = true;
                double value = 0D;
                try {
                    if (Objects.equals(objectJsonObject.getString(key), BasicConstant.NULL_SHOW_STR)) {
                        visible = false;
                    } else {
                        value = objectJsonObject.getDoubleValue(key);
                    }
                } catch (Exception e) {
                    value = 0D;
                }
                if (visible) {
                    if (!rateNumFlag) {
                        resultJsonObject.put(key, attrDecimalPrecisionHelper.formatPrecisionWithIntegerOnly(value, fieldAttrEntity));
                    } else {
                        String decPrecision = attrDecimalPrecisionHelper.setDecPrecision(value * 100, fieldAttrEntity.getAccuracy());
                        resultJsonObject.put(key, decPrecision + "%");
                    }
                }
            }
        }else if(Objects.equals(fieldType,FieldTypeEnum.PRODUCT_STOCK.getType()) && Objects.nonNull(objectJsonObject.get(key))){
            // 小数精度
            double value;
            try {
                value = objectJsonObject.getDoubleValue(key);
            } catch (Exception e) {
                value = 0D;
            }
            if (!rateNumFlag) {
                resultJsonObject.put(key, attrDecimalPrecisionHelper.formatPrecisionWithIntegerOnly(value, fieldAttrEntity));
            } else {
                String decPrecision = attrDecimalPrecisionHelper.setDecPrecision(value * 100, fieldAttrEntity.getAccuracy());
                resultJsonObject.put(key, decPrecision + "%");
            }
        }else if (Objects.equals(fieldType, FieldTypeEnum.ACCOUNT_PERIOD.getType())) {
            String periodJsonStr = objectJsonObject.getString(key);
            String periodJsonObj = fundSetHelp.getFormatReceivablePeriod(periodJsonStr);
            resultJsonObject.put(key, periodJsonObj);
        } else if (Objects.equals(fieldType, FieldTypeEnum.CHECK_DATE.getType())) {
            JSONObject checkDateObj = objectJsonObject.getJSONObject(key);
            String startTime = DateTimeUtil.getString(checkDateObj.getLongValue("startTime") * 1000, DateTimeUtil.SDFDate);
            String endTime = DateTimeUtil.getString(checkDateObj.getLongValue("endTime") * 1000, DateTimeUtil.SDFDate);
            String checkDate = startTime + " 至 " + endTime;
            resultJsonObject.put(key, checkDate);
        } else if (Objects.equals(saasAttr, ContactEnum.PHONE.getSaasAttr())) {
            formDataAnalysisHelp.analysisTelephoneNumber(fieldAttrEntity, objectJsonObject, resultJsonObject, analysisDataDTO.getLoginUser());
        } else if(Objects.equals(fieldType, FieldTypeEnum.TEMPLATE_FIELD.getType())){
            analysisTemplateFieldHelp.analysisTemplateField4Map(resultJsonObject, fieldAttrEntity.getAttr(),analysisDataDTO.getTemplateFieldMap());
        } else {
            resultJsonObject.put(key, objectJsonObject.get(key));
        }
    }

    /**
     * 处理标签展示
     * @param analysisDataDTO
     * @param key
     * @param objectJsonObject
     * @param resultJsonObject
     */
    private void analasisLabel(AnalysisDataDTO analysisDataDTO, String key, JSONObject objectJsonObject, JSONObject resultJsonObject) {
        JSONArray jsonArray = objectJsonObject.getJSONArray(key);
        List<Long> longs = JSON.parseArray(jsonArray.toJSONString(), Long.class);
        List<LabelEntity> labelEntities = labelModel.getByLabelIds(longs, analysisDataDTO.getCorpid());
        List<LabelForDetailUpadatePojo> labelForDetailUpadatePojos = new ArrayList<>();

        labelEntities.forEach(item -> {
            LabelForDetailUpadatePojo labelForDetailUpadatePojo = new LabelForDetailUpadatePojo();
            labelForDetailUpadatePojo.setColor(item.getColor());
            labelForDetailUpadatePojo.setName(item.getName());
            labelForDetailUpadatePojo.setId(item.getId());
            labelForDetailUpadatePojos.add(labelForDetailUpadatePojo);
        });
        resultJsonObject.put(key, labelForDetailUpadatePojos);
    }

    /**
     * 红冲合同的计划收款金额、未收金额、坏账金额默认值情况下为0 为了保持和saas以前的一样 这里要改成 --
     * @param formDataListVO
     */
    public void redPaymentShowHandle(PaasFormDataEsListVO formDataListVO){
        if(BusinessFieldEnum.PAYMENT.getBusinessType().equals(formDataListVO.getBusinessType())) {
            List<PaasFormDataEntityExt> paasFormDataEntityExts = formDataListVO.getPaasFormDataESList();
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                JSONObject resultJson = paasFormDataEntityExt.getData();
                Double zero = 0D;
                if (resultJson.containsKey(PaymentEnum.IS_RED.getAttr())) {
                    if (IsRedEnum.RED.getCode().equals(resultJson.getInteger(PaymentEnum.IS_RED.getAttr()))) {
                        if (zero.equals(resultJson.getDouble(PaymentEnum.AMOUNT.getAttr()))) {
                            resultJson.put(PaymentEnum.AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                        }
                        if (zero.equals(resultJson.getDouble(PaymentEnum.UN_AMOUNT.getAttr()))) {
                            resultJson.put(PaymentEnum.UN_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                        }
                        if (zero.equals(resultJson.getDouble(PaymentEnum.BAD_AMOUNT.getAttr()))) {
                            resultJson.put(PaymentEnum.BAD_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                        }
                        if (zero.equals(resultJson.getDouble(PaymentEnum.INVOICE_AMOUNT.getAttr()))) {
                            resultJson.put(PaymentEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                        }
                    }
                }
            }
        }
    }

    /**
     * 单独拎出来 解析千份位 测试完后再放出
     * @param formDataListVO
     * @throws XbbException
     */
    public void analysisAmountOfThousandBits(PaasFormDataEsListVO formDataListVO, Boolean analysisAmountOfThousandBitsWithOriginalValue){
        List<PaasFormDataEntityExt> paasFormDataEntityExts = formDataListVO.getPaasFormDataESList();
        List<FieldAttrEntity> fieldAttrEntityList = formDataListVO.getHeadList();
        Map<String,Object> explainMap = FormDataAnalysisHelp.needAnalysisFieldAttr(fieldAttrEntityList);
        for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
            JSONObject resultJson = paasFormDataEntityExt.getData();
            Iterator iterator = resultJson.keySet().iterator();
            while (iterator.hasNext()){
                String attr = iterator.next().toString();
                formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(resultJson,attr,explainMap,analysisAmountOfThousandBitsWithOriginalValue);
            }
            paasFormDataEntityExt.setData(resultJson);
        }
    }
    /**
     * 单独拎出来 解析千份位 测试完后再放出
     * @param formDataListVO
     * @throws XbbException
     */
    public void analysisAmountOfThousandBits(List<PaasFormDataEntityExt> paasFormDataEntityExts, Map<Long, List<FieldAttrEntity>> formExplainListMap, Boolean analysisAmountOfThousandBitsWithOriginalValue){
        Map<Long, Map<String, Object>> explainMap = FormDataAnalysisHelp.needAnalysisFieldAttr(formExplainListMap);

        for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
            if (!explainMap.containsKey(paasFormDataEntityExt.getFormId())) {
                continue;
            }
            JSONObject resultJson = paasFormDataEntityExt.getData();
            Iterator iterator = resultJson.keySet().iterator();
            while (iterator.hasNext()){
                String attr = iterator.next().toString();
                formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(resultJson,attr,explainMap.get(paasFormDataEntityExt.getFormId()),analysisAmountOfThousandBitsWithOriginalValue);
            }
            paasFormDataEntityExt.setData(resultJson);
        }
    }

    /**
     * 查询跟进时间样式
     * @param formConfigGetDTO
     * @throws XbbException
     * @return 0:false  1: true
     */
    public Map<String, String> lastConnectTime(FormConfigGetDTO formConfigGetDTO) throws XbbException {
        Map<String, String> lastConnectTimeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String customerLastConnectTime = "0";
        String corpid = formConfigGetDTO.getCorpid();
        Integer businessType = formConfigGetDTO.getBusinessType();
        Long formId = formConfigGetDTO.getFormId();

        if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(ParameterConstant.CORPID, corpid);
            map.put(StringConstant.BUSINESS_TYPE, businessType);
            map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            map.put(ParameterConstant.FORMID, formId);
            List<FormConfigEntity> formConfigEntities = formConfigModel.findEntitys(map);

            String formConfig = null;
            for(FormConfigEntity entity : formConfigEntities) {
                if(Objects.equals(entity.getConfig(), FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig())) {
                    formConfig = FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig();
                    customerLastConnectTime = entity.getConfigValue();
                    lastConnectTimeMap.put(formConfig, customerLastConnectTime);
                }
                if(Objects.equals(entity.getConfig(), FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig())) {
                    formConfig = FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig();
                    customerLastConnectTime = entity.getConfigValue();
                    lastConnectTimeMap.put(formConfig, customerLastConnectTime);
                }
                if(Objects.equals(entity.getConfig(), FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig())) {
                    formConfig = FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig();
                    customerLastConnectTime = entity.getConfigValue();
                    lastConnectTimeMap.put(formConfig, customerLastConnectTime);
                }
            }
            if(lastConnectTimeMap.isEmpty()){
                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    lastConnectTimeMap.put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig(), "1");
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())) {
                    lastConnectTimeMap.put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig(), "0");
                }
                if(Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
                    lastConnectTimeMap.put(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig(), "1");
                }
                if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                    lastConnectTimeMap.put(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig(), "1");
                }
            }
        }
        return lastConnectTimeMap;
    }

    /**
     * 获取客户主联系人电话权限
     *
     * @param corpid 公司id
     * @param formDataListDTO 入参
     * @param customerIds 客户ids
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-07 15:45
     * @since v1.0
     * @version v1.0
     */
    public Map<Long, Boolean> analysisContactForCustomer(String corpid, FormDataListDTO formDataListDTO, List<Long> customerIds) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }

        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach(item -> {
            explainMap.put(item.getAttr(), item);
        });

        List<String> customerIdIn = new ArrayList<>();
        for(Long customerId : customerIds) {
            customerIdIn.add(customerId.toString());
        }
        // 数据
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        // 添加corpid,formId,del
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        //无需审批和通过
        boolQueryBuilder.filter(termsQuery("flowStatus", FlowStatusEnum.getStatisticType()));
        boolQueryBuilder.filter(termsQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), customerIdIn));
        boolQueryBuilder.filter(termQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.IS_MAIN), BasicConstant.ONE));

        // 客户id，联系人电话，创建人，负责人，联系人id
        List<String> fieldList = new ArrayList<>();
        fieldList.add("data." + ContactEnum.CUSTOMER_NAME.getAttr());
        fieldList.add("data." + ContactEnum.PHONE.getAttr());
        fieldList.add(ContactEnum.CREATOR_ID.getAttr());
        fieldList.add("data." + ContactEnum.OWNER_ID.getAttr());
        fieldList.add(FieldTypeEnum.DATAID.getAlias());

        XbbAggregatedPage aggregatedPage;
        try {
           aggregatedPage = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_CONTACT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList, formDataListDTO.getPage(), formDataListDTO.getPageSize(), null);
        } catch (XbbException e) {
            aggregatedPage = null;
        }
        if (Objects.isNull(aggregatedPage)) {
            return new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        List<PaasFormDataEntityExt> formDataEsList = aggregatedPage.getContent();
        if(Objects.isNull(formDataEsList) || formDataEsList.isEmpty()) {
            return new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }

        List<Long> dataIdList = new ArrayList<>();
        for(PaasFormDataEntityExt item: formDataEsList) {
            dataIdList.add(item.getDataId());
        }
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(dataIdList,corpid,XbbRefTypeEnum.CONTACT.getCode(),false,mainUserMap,coUserMap);

        Map<Long, Boolean> phoneFieldMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        FieldAttrEntity phoneEntity = explainMap.get(ContactEnum.PHONE.getAttr());
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);

        for (PaasFormDataEntityExt paasFormDataEsEntity: formDataEsList){

            handlerExplainDTO.setCreatorId(paasFormDataEsEntity.getCreatorId());
            handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>()));
            handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(paasFormDataEsEntity.getDataId(), new ArrayList<>()));

            JSONObject dataJsonObject = paasFormDataEsEntity.getData();
            boolean hidePhoneFlag = ExplainUtil.fieldAttrHide(phoneEntity, handlerExplainDTO);
            phoneFieldMap.put(dataJsonObject.getLong(ContactEnum.CUSTOMER_NAME.getAttr()), !hidePhoneFlag);

        }

        return phoneFieldMap;
    }

    protected void setAchived(FormDataListDTO formDataListDTO, JSONObject resultObject, PaasFormDataEntityExt paasFormDataEsEntity) {
        if (Objects.equals(formDataListDTO.getPlatform(), StringConstant.PLATFORM_DINGTALK)) {
            Integer businessType = formDataListDTO.getBusinessType();
            // 移动端，客户、机会、合同、报价单 加上 ‘归’ 字标签 (注：web端tagData已经赋过值，不做处理)
            JSONObject tagData = new JSONObject();
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(CustomerManagementEnum.IS_ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(SalesOpportunityEnum.IS_ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(ContractEnum.ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(QuotationEnum.ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(ClueEnum.IS_ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr()));
            } else if (Objects.equals(businessType, XbbRefTypeEnum.ORDER.getCode())) {
                tagData.put("isAchived", resultObject.getInteger(OrderEnum.ARCHIVED.getAttr()));
            }
            if (!tagData.isEmpty()) {
                paasFormDataEsEntity.setTagData(tagData);
            }
        }
    }


    /**
     * 解析数据
     * @param formDataListVO
     * @throws XbbException
     */
    public void analysisOuterLinkDataList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {

        try {
            String corpid = formDataListDTO.getCorpid();
            Integer businessType = formDataListDTO.getBusinessType();

            FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
            formConfigGetDTO.setCorpid(corpid);
            formConfigGetDTO.setBusinessType(businessType);
            formConfigGetDTO.setFormId(formDataListDTO.getFormId());
            Map<String, String> lastConnectTimeMap = lastConnectTime(formConfigGetDTO);

            List<PaasFormDataEntityExt> formDataEsList = formDataListVO.getPaasFormDataESList();

            List<PaasFormDataEntityExt> resultEntity = new ArrayList<>();
            // 产品分类
            Map<Long, String> categoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            boolean isProduct = Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode());
            if (isProduct) {
                categoryMap = productCategoryModel.categoryList(formDataListDTO.getCorpid());
            }
            String labelAttr =null;
            for (FieldAttrEntity fieldAttrEntity : formDataListVO.getHeadList()) {
                if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    labelAttr = fieldAttrEntity.getAttr();
                    break;
                }
            }
            Map<Long, LabelPojo> labelPojoMap = labelHelp.getLabelMap(formDataListDTO.getFormId(), formDataListDTO.getCorpid(), formDataListDTO.getAppId());
            List<Long> dataIds = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity: formDataEsList){
                dataIds.add(paasFormDataEsEntity.getId());
                JSONObject dataJsonObject = paasFormDataEsEntity.getData();
                if (Objects.nonNull(paasFormDataEsEntity.getOriginData())) {
                    dataJsonObject = paasFormDataEsEntity.getOriginData();
                    paasFormDataEsEntity.setOriginData(null);
                }
                dataJsonObject.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEsEntity.getAddTime());
                dataJsonObject.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEsEntity.getUpdateTime());
                dataJsonObject.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                // 客户最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    dataJsonObject.put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig()));
                }
                // 销售机会最后跟进时间标识
                if(Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
                    dataJsonObject.put(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig()));
                }
                // 产品分类的解析
                if (isProduct) {
                    Long categoryId = dataJsonObject.getLong(ProductEnum.CATEGORY_ID.getAttr());
                    dataJsonObject.put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(categoryId, ""));
                }
                labelHelp.dealId2Pojo4One(labelAttr,dataJsonObject, labelPojoMap);
                JSONObject cloneData = (JSONObject)dataJsonObject.clone();
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataListDTO, parseSingleRowDataDTO);

                Long dataId = paasFormDataEsEntity.getId();
                paasFormDataEsEntity.setDataId(dataId);


                parseSingleRowDataDTO.setDataJsonObject(cloneData);
                // 为了在列表上面可以更新数据，加下这个
                ParseSingleRowDataVO updateDataVo = parseOuterLinkSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(updateDataVo)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                JSONObject sourceData = updateDataVo.getResult();

                paasFormDataEsEntity.setData(sourceData);

                sourceData.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                paasFormDataEsEntity.setSourceData(sourceData);


                resultEntity.add(paasFormDataEsEntity);

            }
            formDataListDTO.setIdIn(dataIds);
            formDataListVO.setPaasFormDataESList(resultEntity);
            formDataListVO.getPageHelper().setRowsCount(resultEntity.size());
        } catch (XbbException e) {
            LOG.error("formDataListAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("formDataListAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    private ParseSingleRowDataVO parseOuterLinkSingleRowData(ParseSingleRowDataDTO parseSingleRowDataDTO) throws XbbException{
        ParseSingleRowDataVO parseSingleRowDataVO = new ParseSingleRowDataVO();

        Map<String, FieldAttrEntity> explainMap = parseSingleRowDataDTO.getExplainMap();
        JSONObject dataJsonObject = parseSingleRowDataDTO.getDataJsonObject();
        JSONObject resultObject = (JSONObject) dataJsonObject.clone();

        AnalysisDataDTO analysisDataDTO = new AnalysisDataDTO();
        BeanUtil.copyProperties(parseSingleRowDataDTO, analysisDataDTO);

        Iterator iterator = resultObject.keySet().iterator();
        while (iterator.hasNext()) {
            String key = Objects.toString(iterator.next());
            FieldAttrEntity fieldAttrEntity = explainMap.get(key);
            if(fieldAttrEntity == null) {
                continue;
            }
            // 子表单的解析
            if(ExplainUtil.isSubForm(fieldAttrEntity.getFieldType())){
                try {
                    JSONArray jsonArray = dataJsonObject.getJSONArray(key) == null ? new JSONArray() : dataJsonObject.getJSONArray(key);
                    JSONArray resultJsonArray = new JSONArray();
                    List<Map<String, Object>> subLinkDataList = new ArrayList<>();
                    Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMapByList(fieldAttrEntity.getSubForm().getItems());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        if (!(jsonArray.get(i) instanceof Map)) {
                            continue;
                        }
                        JSONObject subJsonObject = jsonArray.getJSONObject(i);
                        Iterator subIterator = subJsonObject.keySet().iterator();
                        JSONObject subResult = new JSONObject();
                        Map<String, Object> subLinkData = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        while (subIterator.hasNext()) {
                            String subKey = Objects.toString(subIterator.next());
                            FieldAttrEntity subFieldAttrEntity = subExplainMap.get(subKey);
                            if (subFieldAttrEntity == null) {
                                subResult.put(subKey, subJsonObject.get(subKey));
                                continue;
                            }
                            analysisDataDTO.setAttr(subKey);
                            analysisDataDTO.setFieldAttrEntity(subFieldAttrEntity);
                            analysisDataDTO.setDataJsonObject(subJsonObject);
                            analysisData(analysisDataDTO, subResult, subLinkData, new HashSet<>());
                        }
                        subLinkDataList.add(subLinkData);
                        resultJsonArray.add(subResult);
                    }
                    resultObject.put(key, resultJsonArray);
                } catch (Exception e) {
                    LOG.warn("formDataListAnalysisDataHelp.parseOuterLinkSingleRowData表单单行数据解析-子表单的解析出错，dataId="+parseSingleRowDataDTO.getDataId()
                            + "--businessType=" + parseSingleRowDataDTO.getBusinessType(), e);
                }
            } else if(Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.BIRTHDAY.getType())){
                String linkedText = fieldAttrEntity.getLinkedText();
                analysisSaasDataListHelp.formatBirthday4Show(dataJsonObject, key, linkedText);
                resultObject.put(key, dataJsonObject.get(key));
            } else if (Objects.equals(FieldTypeEnum.SWITCH.getType(), fieldAttrEntity.getFieldType())) {
                if (Objects.equals(dataJsonObject.getString(key), BasicConstant.ZERO.toString())) {
                    resultObject.put(key, OperateTypeEnum.NO.getName());
                }else {
                    resultObject.put(key, OperateTypeEnum.YES.getName());
                }
            } else {
                try {
                    analysisDataDTO.setAttr(key);
                    analysisDataDTO.setFieldAttrEntity(fieldAttrEntity);
                    analysisDataDTO.setDataJsonObject(dataJsonObject);
                    analysisData(analysisDataDTO, resultObject, new JSONObject(), new HashSet<>());
                } catch (Exception e) {
                    LOG.warn("formDataListAnalysisDataHelp.parseOuterLinkSingleRowData表单单行数据解析-常规，dataId="+parseSingleRowDataDTO.getDataId()
                            + "--businessType=" + parseSingleRowDataDTO.getBusinessType(), e);
                }
            }
            parseSingleRowDataVO.setResult(resultObject);
        }
        return parseSingleRowDataVO;
    }

    public void setAddress(JSONObject addressJsonObject, FieldAttrEntity fieldAttrEntity) {
        if (Objects.nonNull(addressJsonObject) && Objects.equals(fieldAttrEntity.getShowDetailAddress(), 0)) {
            addressJsonObject.put(BusinessConstant.ADDRESS, "");
        }
    }

    /**
     * 合并地址数据
     * @param key attr
     * @param jsonObject 地址对象
     * @param resultJsonObject 保存结果
     */
    public void mergeFullAddressData(String  key, JSONObject jsonObject, JSONObject resultJsonObject) {
        if(jsonObject == null) {
            resultJsonObject.put(key, "");
            return;
        }

        String province = jsonObject.getString(PaasConstant.PROVINCE) != null ? jsonObject.getString(PaasConstant.PROVINCE) : "";
        String city = jsonObject.getString(PaasConstant.CITY) != null ? jsonObject.getString(PaasConstant.CITY) : "";
        String district = jsonObject.getString(PaasConstant.DISTRICT) != null ? jsonObject.getString(PaasConstant.DISTRICT) : "";
        String address = jsonObject.getString(PaasConstant.ADDRESS) != null ? jsonObject.getString(PaasConstant.ADDRESS) : "";

        resultJsonObject.put(key, province + city + district + address);
    }

    /**
     * 批量打标签按钮和批量移除标签
     *      产品这样设计的
     * 方法来自 -> com.xbongbong.paas.help.FormDataListSearchHelp#dealLabelBatch(com.xbongbong.paas.pojo.dto.FormDataListDTO, java.util.List)
     * 暂时放这里，后面再改位置
     * @param formDataListDTO
     * @param batchButtonList
     * @throws XbbException
     */
    public void dealLabelBatch(FormDataListDTO formDataListDTO, List<ButtonPojo> batchButtonList) throws XbbException {

        // 回收站不支持编辑
        List<Integer> comparables = Arrays.asList(XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode(), XbbRefTypeEnum.CLUE_RECYCLE.getCode());
        if (comparables.contains(formDataListDTO.getSubBusinessType())){
            return;
        }

        // 特殊两个批量按钮,批量打标签,批量移除标签
        FieldAttrEntity labelField = null;
        Map<String, FieldAttrEntity> explainMap = formDataListDTO.getExplainMap();
        if (Objects.nonNull(explainMap)) {
            // 获取标签fieldAttrEntity
            for(FieldAttrEntity fieldAttrEntity :explainMap.values()){
                if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())){
                    labelField = fieldAttrEntity;
                    break;
                }
            }
        }
        if (Objects.nonNull(labelField)) {
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
            // 高级权限可编辑并且高级权限可见，并且字段是可见的 就展示这两个按钮
            if (Objects.equals(labelField.getVisible(),1) && ExplainUtil.isEditableOfScope(labelField, handlerExplainDTO) && (!ExplainUtil.invisibleOfScope(labelField, handlerExplainDTO))){
                // -----判断是否有该业务或者该表单的编辑权限，开始
                VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO();
                BeanUtil.copyProperties(formDataListDTO, verifyUpdatePermissionDTO);
                UserVO userVO = verifyUpdatePermissionDTO.getLoginUser();
                if (Objects.equals(SaasMarkEnum.SAAS.getCode(), formDataListDTO.getSaasMark())) {
                    Integer businessType = verifyUpdatePermissionDTO.getBusinessType();
                    UpdateProPermissionAliasEnum updateProPermissionAliasEnum = UpdateProPermissionAliasEnum.getByCode(businessType);
                    if (Objects.nonNull(updateProPermissionAliasEnum)) {
                        if (!userVO.getPermSet().contains(updateProPermissionAliasEnum.getAlias())) {
                            return;                        }
                    }
                } else {
                    Set<Long> idSet = ProPermissionHelp.getPaasEditMenuIdSet(userVO.getPaasPermissions());
                    if (!userVO.isAdminOrBoss() && !idSet.contains(verifyUpdatePermissionDTO.getMenuId())) {
                        return;
                    }
                }
                if (Objects.equals(labelField.getIsOpen(), BasicConstant.ZERO)){
                    return;
                }
                // -----判断是否有该业务或者该表单的编辑权限，结束

                ButtonPojo buttonPojo = new ButtonPojo();
                buttonPojo.setAttr(SaasButtonEnum.ADD_LABEL.getAttr());
                buttonPojo.setValue(SaasButtonEnum.ADD_LABEL.getValue());
                batchButtonList.add(buttonPojo);
                ButtonPojo buttonPojo1 = new ButtonPojo();
                buttonPojo1.setAttr(SaasButtonEnum.REMOVE_LABEL.getAttr());
                buttonPojo1.setValue(SaasButtonEnum.REMOVE_LABEL.getValue());
                batchButtonList.add(buttonPojo1);
            }
        }
    }


    /**
     * 根据linkDataSet和subFormLinkDataMap中的字段拿到关联数据id，返回封装在中linkDataIdMap
     * @param data 数据
     * @param subFormLinkDataMap 子表单中的关联数据字段或者关联产品的关联数据 {"subForm_1": ["text_1", "text2"]}或者 {"array_4": ["text_1"]}
     * @param linkDataSet 主数据的关联数据字段 ["text_1", "text2"]
     * @param linkDataIdSet 所有的关联数据id
     * @param linkDataAttrSet 所有的关联数据的字段，包括子表单和关联产品内的关联数据，以及子表单和关联产品外的关联数据
     * @param linkDataIdMap 返回格式：{"text_1": [23,25,36], "subForm_1": [{"text_1": [23,25,36]}, {"text_2": [23,25,36]}]}
     * @return void
     * @author 吴峰
     * @date 2022/5/11 21:20
     * @throws XbbException
     */
    public static void getLinkDataSet(JSONObject data, Map<String, Set<String>> subFormLinkDataMap, Set<String> linkDataSet,
                                      Set<Object> linkDataIdSet, Set<String> linkDataAttrSet, Map<String, Object> linkDataIdMap) {
        if (Objects.isNull(data)) {
            return;
        }
        if (CollectionsUtil.isNotEmpty(linkDataAttrSet)) {
            // 先处理子表单的数据
            Iterator<String> iterator = subFormLinkDataMap.keySet().iterator();
            while (iterator.hasNext()) {
                String attr = iterator.next();
                Set<String> linkDataAttr = subFormLinkDataMap.get(attr); // 子表单内的关联数据字段
                JSONArray jsonArray = data.getJSONArray(attr);
                if (CollectionsUtil.isNotEmpty(jsonArray)) {

                    Map<String, Set<Long>> subLinkDataIdMap = new HashMap<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        if (!(jsonArray.get(i) instanceof JSONObject)){
                            continue;
                        }
                        JSONObject jsonObject = jsonArray.getJSONObject(i); // 子表单的一行数据
                        for (String item : linkDataAttr) {
                            // 子表单内的关连单选
                            if (jsonObject.get(item) instanceof Number && !Objects.equals(jsonObject.getLong(item), 0L)) {
                                Long id = jsonObject.getLong(item);
                                if (Objects.nonNull(id)) {
                                    linkDataIdSet.add(id); // 这个有什么用呢，关联表不一样的话还会存在相同的id被覆盖的情况，看了下好像就是用来判断下有没有关联数据需要处理
                                    if (subLinkDataIdMap.containsKey(item)) {
                                        List<Long> set = JSON.parseArray(JSON.toJSONString(subLinkDataIdMap.get(item)), Long.class);
                                        set.add(id);
                                        subLinkDataIdMap.put(item, new HashSet<>(set));
                                    } else {
                                        Set<Long> set = new HashSet<>();
                                        set.add(id);
                                        subLinkDataIdMap.put(item, set);
                                    }
                                }
                            }

                            // 子表单内的关连多选
                            if (jsonObject.get(item) instanceof JSONArray || jsonObject.get(item) instanceof ArrayList || jsonObject.get(item) instanceof List) {
                                List<Long> dataArray = new ArrayList<>();
                                try {
                                    dataArray = JSON.parseArray(jsonObject.getString(item), Long.class);
                                } catch (Exception e) {
                                    LOG.error("关联数据多选解析异常", e);
                                }
                                if (dataArray.size() > 0) {
                                    linkDataIdSet.addAll(dataArray);
                                    if (subLinkDataIdMap.containsKey(item)) {
                                        List<Long> set = JSON.parseArray(JSON.toJSONString(subLinkDataIdMap.get(item)), Long.class);
                                        set.addAll(dataArray);
                                        subLinkDataIdMap.put(item, new HashSet<>(set));
                                    } else {
                                        Set<Long> set = new HashSet<>();
                                        set.addAll(dataArray);
                                        subLinkDataIdMap.put(item, set);
                                    }
                                }
                            }
                        }
                    }

                    if (linkDataIdMap.containsKey(attr)) {
                        JSONArray list = JSON.parseArray(JSON.toJSONString(linkDataIdMap.get(attr)));
                        list.add(subLinkDataIdMap);
                        linkDataIdMap.put(attr, list);
                    } else if (!subLinkDataIdMap.isEmpty()){
                        JSONArray subLinkDataList = new JSONArray();
                        subLinkDataList.add(subLinkDataIdMap);
                        linkDataIdMap.put(attr, subLinkDataList);
                    }
                }
            }

            // 在处理主数据
            for (String item : linkDataSet) {
                // 主数据的关连单选
                if (data.get(item) instanceof Number && !Objects.equals(data.getLong(item), 0L)) {
                    Long id = data.getLong(item);
                    if (Objects.nonNull(id)) {
                        linkDataIdSet.add(id);
                        if (linkDataIdMap.containsKey(item)) {
                            List<Long> set = JSON.parseArray(JSON.toJSONString(linkDataIdMap.get(item)), Long.class);
                            set.add(id);
                            linkDataIdMap.put(item, new HashSet<>(set));
                        } else {
                            Set<Long> set = new HashSet<>();
                            set.add(id);
                            linkDataIdMap.put(item, set);
                        }
                    }
                }

                // 主数据的关连多选
                if (data.get(item) instanceof JSONArray || data.get(item) instanceof ArrayList || data.get(item) instanceof List) {
                    List<Long> dataArray = new ArrayList<>();
                    try {
                        dataArray = JSON.parseArray(data.getString(item), Long.class);
                    } catch (Exception e) {
                        LOG.error("关联数据多选解析异常", e);
                    }
                    if (dataArray.size() > 0) {
                        linkDataIdSet.addAll(dataArray);
                        if (linkDataIdMap.containsKey(item)) {
                            List<Long> set = JSON.parseArray(JSON.toJSONString(linkDataIdMap.get(item)), Long.class);
                            set.addAll(dataArray);
                            linkDataIdMap.put(item, new HashSet<>(set));
                        } else {
                            Set<Long> set = new HashSet<>(dataArray);
                            linkDataIdMap.put(item, set);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取关联数据字段，返回封装在linkDataSet和subFormLinkDataMap
     * @param linkDataAttrSet 所有的关联数据字段 格式： ["subForm_1.text_1", "array_1.text_1", "text_1"]
     * @param linkDataSet ["text_1", "text2"]
     * @param subFormLinkDataMap {"subForm_1": ["text_1", "text2"]}或者 {"array_4": ["text_1"]}
     */
    public static void getLinkDataField(Set<String> linkDataAttrSet, Set<String> linkDataSet, Map<String, Set<String>> subFormLinkDataMap) {
        //  分割符号 subForm表示子表单 / array表是关联产品
        Set<String> regexList = new HashSet<>();//子表单关联数据字段得外层子表单字段
        linkDataAttrSet.forEach(item->{
            if ( item.contains(".") && (item.contains(EsAliasEnum.ARRAY.getEsAlias()) || item.contains(EsAliasEnum.SUB_FORM.getEsAlias()))) {
                regexList.add(item.split("\\.")[0]);
            }
        });

        for (String item : linkDataAttrSet) {
            List<String> list = ExplainUtil.getAttrByPoint(item);
            if (Objects.equals(list.size(), BasicConstant.TWO)) {
                item= list.get(0);
            }
            if (regexList.contains(item)) {
                if (subFormLinkDataMap.containsKey(item)) {
                    Set<String> subLinkDataSet = subFormLinkDataMap.get(item);
                    subLinkDataSet.add(list.get(1));
                    subFormLinkDataMap.put(item, subLinkDataSet);
                } else {
                    Set<String> subLinkDataSet = new HashSet<>();
                    subLinkDataSet.add(list.get(1));
                    subFormLinkDataMap.put(item, subLinkDataSet);
                }
            } else {
                linkDataSet.add(item);
            }
        }
    }

    /**
     * 获取关联数据字段，返回封装在linkDataSet和subFormLinkDataMap
     * @param linkDataAttrSet 所有的关联数据字段 格式： ["subForm_1.text_1", "array_1.text_1", "text_1"]
     * @param regex 分割符号 subForm表示子表单 / array表是关联产品
     * @param linkDataSet ["text_1", "text2"]
     * @param subFormLinkDataMap {"subForm_1": ["text_1", "text2"]}或者 {"array_4": ["text_1"]}
     */
    public static void getLinkDataField(Set<String> linkDataAttrSet, String regex, Set<String> linkDataSet, Map<String, Set<String>> subFormLinkDataMap) {
        for (String item : linkDataAttrSet) {
            if (item.contains(regex)) {
                String[] attrArray = item.split("\\.");
                String attr = attrArray[0];
                if (subFormLinkDataMap.containsKey(attr)) {
                    Set<String> subLinkDataSet = subFormLinkDataMap.get(attr);
                    subLinkDataSet.add(attrArray[1]);
                    subFormLinkDataMap.put(attr, subLinkDataSet);
                } else {
                    Set<String> subLinkDataSet = new HashSet<>();
                    subLinkDataSet.add(attrArray[1]);
                    subFormLinkDataMap.put(attr, subLinkDataSet);
                }
            } else {
                linkDataSet.add(item);
            }
        }
    }
}
